package cn.bonoon.controllers;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.bonoon.handler.impl.DefaultLoginSuccessRedirect;
import cn.bonoon.kernel.menus.LoginPageDefinition;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.security.AuthenticatedUserDetails;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.util.StringHelper;

@Controller
@RequestMapping("/s/login")
public class LoginController extends AuthenticatedUserDetails implements InitializingBean{
	
	@Autowired
	private ModuleManager moduleManager;

	private DefaultLoginSuccessRedirect defaultLoginSuccessRedirect;
	
	static final String[] ERRORS = {"用户名、密码或验证码有误！", "本账户已经在其它地方登录！", "登录超时"};
	
	private static final String DEFAULT_LOGIN_LAYOUT = "login/layout-login.vm";
	private static final String DEFAULT_INDEX = "login/login";
	
	private String layout = DEFAULT_LOGIN_LAYOUT, index = DEFAULT_INDEX;
	private String title, name, foot, logo;

	@Value("${default.home.url}")
	private String homeUrl;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		LoginPageDefinition li = moduleManager.loginPage();
		title = li.getName();
		name = li.getName();
		foot = li.getFoot();
		logo = li.getLogo();
		
		String ll = li.getLayout();
		if(StringHelper.isNotEmpty(ll)){
			layout = ll;
		}
	}

	private String _attributes(Model model) {
		model.addAttribute("layout", layout);
		model.addAttribute("title", title);
		model.addAttribute("name", name);
		model.addAttribute("foot", foot);
		model.addAttribute("logo", logo);
	
		//model.addAttribute("modulus", RSAManager.rsaManager.getModulus());
		//model.addAttribute("exponent", RSAManager.rsaManager.getExponent());
		
		return index;
	}
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "error", method = RequestMethod.GET)
	public String loginError(Model model, HttpServletRequest request,
			@RequestParam(value = "t", required = false) Integer t) {
		
		Object obj = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

		if(obj instanceof BadCredentialsException){
			model.addAttribute("error", ERRORS[0]);
		}else if(obj instanceof AuthenticationException){
			AuthenticationException exception = (AuthenticationException)obj;
			model.addAttribute("error", exception.getMessage());
		}else{
			int i = null != t && t < ERRORS.length ? t.intValue() : 0;
			model.addAttribute("error", ERRORS[i]);
		}
		
		
		return _attributes(model);
	}
	
	@RequestMapping(value = "timeout", method = { GET, POST })
	public String loginTimeout(Model model){
		model.addAttribute("error", ERRORS[2]);
		return _attributes(model);
	}
	
	@RequestMapping(value = "expired", method = RequestMethod.GET)
	public String loginExpired(Model model){
		model.addAttribute("error", ERRORS[1]);
		return _attributes(model);
	}
	
	/**
	 * 登录
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String login(
			HttpServletRequest request,
			HttpServletResponse response,
			Model model){
		//对当前是否已经登录进行判断，如果已经登录，则跳转到默认的界面
		LogonUser user = getUser();
		if(null != user){
			//已经登录
			if(null == defaultLoginSuccessRedirect){
				return "redirect:" + homeUrl;
			}
			return defaultLoginSuccessRedirect.redirectUrl(request, response, user);
//			if(user.allowAccess()){
//				return "redirect:" + moduleManager.getEndpoint();
//			}else{
//				return "redirect:" + moduleManager.getDefaultEndpoint();
//			}
		}
		return _attributes(model);
	}
}
